package com.itheima.stargraph.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.stargraph.dto.request.UserLoginReqDTO;
import com.itheima.stargraph.dto.respone.UserLoginResDTO;
import com.itheima.stargraph.mapper.UserMapper;
import com.itheima.stargraph.pojo.User;
import com.itheima.stargraph.service.UserService;
import com.itheima.stargraph.utils.JWTUtils;
import org.springframework.stereotype.Service;

/**
 * TODO
 *
 * @Author huang
 * @Date 2025/6/11 2025/6/11
 */
@Service
public class ImplUserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public UserLoginResDTO login(UserLoginReqDTO dto) {
        //根据账号(包括手机号用户名)查询用户
        User user = this.lambdaQuery().eq(User::getUsername, dto.getUsername()).or()
                .eq(User::getMobile, dto.getPhone()).one();
        if (user==null){
            throw new RuntimeException("账号密码错误");
        }
        //判断密码是否正确
        boolean checkpw = BCrypt.checkpw(dto.getPassword(), user.getPassword());
        if (!checkpw){
            throw new RuntimeException("账号密码错误");
        }
        //判断用户状态是否为登录态
        if (user.getStatus()!=0){
            throw new RuntimeException("非法用户");
        }
        //生成用户令牌
        String token = JWTUtils.createJWT(user.getId(), user.getUsername());
        //封装返回数据
        return UserLoginResDTO.builder()
                .id(user.getId())
                .name(user.getUsername())
                .avatar(user.getAvatar())
                .token(token)
                .build();

    }
}
